package org.zhangsh.bio;

import org.zhangsh.socket.HostInfo;

import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * </p>
 *
 * @author zhangsh
 * @version 1.0.0
 * @since 2019-04-18
 */
public class BioEchoServer {

    private static class EchoClientHandler implements Runnable{

        private Scanner scanner;
        private PrintStream out;

        // 每个客户端需要启动一个task
        private Socket clinet;
        public EchoClientHandler(Socket clinet){
            this.clinet = clinet;
            try {
                // 客户端的输入，也就是处理客户端的输入
                this.scanner = new Scanner(this.clinet.getInputStream());
                this.scanner.useDelimiter("\n");
                // 客户端的输出，也就是往客户端输出
                this.out = new PrintStream(this.clinet.getOutputStream());

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {

            boolean flag = true;
            for(;;){
                if(this.scanner.hasNext()){
                    String val = this.scanner.next().trim();
                    System.out.println("[server]获取客户端信息："+ val);
                    // 客户端想要bye
                    if("bye".equals(val)){
                        System.out.println("[server]server给你回复byebye");
                        this.out.println("byebye");
                        break;
                    }else {
                        this.out.println("[ECHO] :" + val);
                    }
                }
            }
            System.out.println("[server] handler线程退出");
            this.scanner.close();
            this.out.close();
            try {
                this.clinet.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) throws Exception{

        ServerSocket serverSocket = new ServerSocket(HostInfo.HOST_PORT);
        System.out.println("服务器监听端口：" + HostInfo.HOST_PORT);

        ExecutorService executorService = Executors.newFixedThreadPool(10);

        for(;;){
            final Socket clinet = serverSocket.accept();
            executorService.submit(new EchoClientHandler(clinet));
        }
//        executorService.shutdown();
//        serverSocket.close();

    }
}
